<template>
  <div class="add-consultation-container">
    <el-card class="form-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">新增看诊记录</span>
        </div>
      </template>

      <el-form
          :model="form"
          :rules="rules"
          ref="formRef"
          label-width="120px"
          class="consultation-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="患者ID" prop="userId">
              <el-input v-model.number="form.userId" placeholder="请输入患者ID" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="医生ID" prop="doctorId">
              <el-input v-model.number="form.doctorId" placeholder="请输入医生ID" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="医院ID" prop="hospitalId">
              <el-input v-model.number="form.hospitalId" placeholder="请输入医院ID" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="就诊日期" prop="visitDate">
              <el-date-picker
                  v-model="form.visitDate"
                  type="date"
                  placeholder="选择就诊日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="诊断" prop="diagnosis">
          <el-input v-model="form.diagnosis" placeholder="请输入诊断结果" clearable />
        </el-form-item>

        <el-form-item label="处方" prop="prescription">
          <el-input v-model="form.prescription" placeholder="请输入处方内容" type="textarea" :rows="3" clearable />
        </el-form-item>

        <el-form-item label="备注" prop="notes">
          <el-input v-model="form.notes" placeholder="请输入其他备注信息" type="textarea" :rows="3" clearable />
        </el-form-item>

        <el-form-item class="form-actions">
          <el-button type="primary" @click="handleSubmit" :icon="Check">提交</el-button>
          <el-button @click="handleReset" :icon="Refresh">重置</el-button>
          <el-button @click="handleGoBack" :icon="Back">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { Check, Refresh, Back } from '@element-plus/icons-vue' // 导入图标

const router = useRouter()
const formRef = ref(null) // 明确初始值为 null

const form = ref({
  userId: null, // 将ID类型设置为null，方便输入框使用v-model.number
  doctorId: null,
  hospitalId: null,
  visitDate: '',
  diagnosis: '',
  prescription: '',
  notes: '',
})

const rules = {
  userId: [
    { required: true, message: '请输入患者ID', trigger: 'blur' },
    { type: 'number', message: '患者ID必须是数字', trigger: 'blur', transform: (value) => Number(value) },
  ],
  doctorId: [
    { required: true, message: '请输入医生ID', trigger: 'blur' },
    { type: 'number', message: '医生ID必须是数字', trigger: 'blur', transform: (value) => Number(value) },
  ],
  hospitalId: [
    { required: true, message: '请输入医院ID', trigger: 'blur' },
    { type: 'number', message: '医院ID必须是数字', trigger: 'blur', transform: (value) => Number(value) },
  ],
  visitDate: [{ required: true, message: '请选择就诊日期', trigger: 'change' }],
  // 诊断、处方、备注不做必填校验，但可以加长度限制等
}

const handleSubmit = async () => {
  // 确保 formRef.value 存在
  if (!formRef.value) {
    ElMessage.error('表单组件未加载完成，请稍后重试。');
    return;
  }

  const valid = await formRef.value.validate().catch(() => false);
  if (!valid) return;

  try {
    const response = await axios.post('http://localhost:8080/visits', form.value);
    if (response.status === 200 || response.status === 201) {
      ElMessage.success('看诊记录添加成功！');
      router.push('/home/consultations'); // 添加成功后跳转回列表页
    } else {
      ElMessage.error('添加失败，请重试。' + (response.data.msg || ''));
    }
  } catch (error) {
    console.error('提交失败:', error);
    ElMessage.error('提交失败，请检查网络或服务器。');
  }
};

const handleReset = () => {
  formRef.value.resetFields();
  // 对于非表单项且需要重置的，可以手动重置
  form.value.userId = null;
  form.value.doctorId = null;
  form.value.hospitalId = null;
};

const handleGoBack = () => {
  router.back(); // 返回上一页
};
</script>

<style scoped>
.add-consultation-container {
  padding: 30px; /* 页面内边距 */
  background-color: #f8fbfd; /* 页面背景色 */
  min-height: calc(100vh - 60px); /* 适应主布局高度 */
  display: flex; /* 使用 flex 布局居中卡片 */
  justify-content: center;
  align-items: flex-start; /* 顶部对齐 */
}

.form-card {
  width: 100%;
  max-width: 800px; /* 限制卡片最大宽度 */
  border-radius: 12px; /* 圆角卡片 */
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.08); /* 柔和阴影 */
  animation: fade-in 0.5s ease-out; /* 入场动画 */
}

@keyframes fade-in {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: translateY(0); }
}

.card-header {
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5; /* 分隔线 */
  margin-bottom: 20px;
}

.card-title {
  font-size: 24px; /* 标题字号 */
  font-weight: bold;
  color: #333;
  text-align: center; /* 标题居中 */
  display: block; /* 确保 span 占据一行以便 text-align 生效 */
}

.consultation-form {
  padding: 0 20px; /* 表单内边距 */
}

.el-form-item {
  margin-bottom: 22px; /* 增大表单项间距 */
}

.el-input,
.el-textarea,
.el-date-picker {
  width: 100%; /* 输入框、文本域、日期选择器宽度铺满 */
}

.el-date-picker {
  display: flex; /* 使日期选择器内部元素水平对齐 */
}

/* 按钮组样式 */
.form-actions {
  margin-top: 30px; /* 增加与上方表单项的间距 */
  text-align: center; /* 按钮居中 */
}

.form-actions .el-button {
  border-radius: 6px; /* 按钮圆角 */
  padding: 10px 20px; /* 按钮内边距 */
  font-size: 15px;
  margin: 0 10px; /* 按钮之间间距 */
}
</style>